import os

def py_list(dirs):
    """返回该目录下python文件的名字"""
    return [x for x in os.listdir(dirs) if os.path.isfile(os.path.join(dirs,x)) and os.path.splitext(x)[1]=='.py']

def hang_counter(path):
    """统计空行数、注释行数、代码行数"""
    with open(path,'r',encoding='UTF-8') as f:
       py = f.readlines()
    counter = 0
    kh_sl = 0
    dm_sl = 0
    zs_sl = 0
    new_py = []
    zs_hs = 0
    sychar = '"""'
    dychar = "'''"
    for i,p in enumerate(py):
        counter+=1
        p = p.replace(" ",'').replace('\t','')  #去掉所有的空格和table

        if (zs_hs-1)>=1:   #处理多行注释问题
            zs_hs-=1
            continue
        else:
            zs_hs = 0

        if p == '\n':   #判断空行
            kh_sl +=1
        if p[0] == '#': #判断注释
            zs_sl+=1
        if p[0:3] == sychar:    #判断3个双引号的多行注释
            if py[i][-4:-1]==sychar and len(py[i])>4:
                zs_sl+=1
            else:
                n = i
                while True:
                    n+=1
                    if (sychar in py[n]):
                        break
                zs_hs=n-i+1
                zs_sl+=zs_hs

        if p[0:3] == dychar:    #判断3个单引号的多行注释
            if py[i][-4:-1]==dychar and len(py[i])>4:
                zs_sl+=1
            else:
                n=i
                while(True):
                    n+=1
                    if (dychar in py[n]):
                        break
                zs_hs=n-i+1
                zs_sl+=n-i+1
        new_py.append(p)
    return kh_sl,zs_sl,counter-kh_sl-zs_sl,counter



def test():
    print(py_list('./test'))


if __name__ == '__main__':
    start_dir = 'test'
    py_lists = py_list(start_dir)
    py_dirs = []
    for py in py_lists:
        py_dirs.append(os.path.join(start_dir,py))

    for i,py in enumerate(py_dirs):
        print('文件:',py_lists[i])
        konghang,zhushi,daima,zong=hang_counter(py)
        print("空行数：%s 注释行数：%s" %(konghang,zhushi))
        print("代码行数：%s 总行数：%s" %(daima,zong),end='\n\n\n')

if False:
    test()
